package com.victor.bookretail.repository;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.victor.bookretail.domain.UserInfoSearchBo;
import com.victor.bookretail.entity.UserInfoPo;
import com.victor.bookretail.mapper.UserInfoMapper;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Repository
public class UserInfoRepository {

    @Resource
    private UserInfoMapper mapper;

    public UserInfoPo insert(UserInfoPo userInfoPo) {
        mapper.insert(userInfoPo);
        return userInfoPo;
    }

    public List<UserInfoPo> query(UserInfoSearchBo searchBo) {
        QueryWrapper<UserInfoPo> queryWrapper = new QueryWrapper<>();
        boolean valid = false;
        if (Objects.nonNull(searchBo.getId())) {
            queryWrapper.eq("id", searchBo.getId());
            valid = true;
        }
        if (StrUtil.isNotEmpty(searchBo.getPhone())) {
            queryWrapper.eq("phone", searchBo.getPhone());
            valid = true;
        }
        if (!valid) {
            return new ArrayList<>();
        }
        return mapper.selectList(queryWrapper);
    }

    public UserInfoPo queryOne(UserInfoSearchBo searchBo) {
        List<UserInfoPo> userInfoPos = query(searchBo);
        return CollectionUtils.isEmpty(userInfoPos) ? null : userInfoPos.get(0);
    }

    /**
     * update the user point with CAS
     *
     * @param currentUserInfoPo user info stored in db
     * @param updatePoint       the value need to store
     * @return true: success  false: update failed
     */
    public boolean updateUserPoint(UserInfoPo currentUserInfoPo, Integer updatePoint) {
        QueryWrapper<UserInfoPo> queryWrapper = new QueryWrapper<>();
        if (Objects.isNull(currentUserInfoPo) || Objects.isNull(updatePoint)) {
            return false;
        }
        queryWrapper.eq("point", currentUserInfoPo.getPoint());
        UserInfoPo updatePo = BeanUtil.copyProperties(currentUserInfoPo, UserInfoPo.class);
        updatePo.setPoint(updatePoint);
        return mapper.update(updatePo, queryWrapper) > 0;
    }

}
